package org.or5e.oss.core;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
/**
 * The Core DB Utility is provided in this class, we have the connection pooling which is used to take from the JNDI of TOMCAT. we need to use the core.properties file to provide the JNDI name, so that this class initilizes the DataSource from that environment.
 * @author Ponraj Suthanthiramani
 */
public class DBUtils extends BaseObject {
	private static DBUtils _utils = null;
	private DataSource _dataSource = null;
	private DBUtils()  {
		try {
			InitialContext context = new InitialContext();
			_dataSource = (DataSource) context.lookup((String) getProperty("dbSource"));
		}
		catch (NamingException e) {
			error(e.getMessage());
		}
	}

	/**
	 * Factory Method, which provides the connection of the Data Source.
	 * @return _utils the DB Utility Instance
	 */
	public static DBUtils getDBUtils() {
		if(_utils == null) {
			_utils = new DBUtils();
		}
		return _utils;
	}
	
	/**
	 * This method provides the way of getting the connection so that any caller can gain access to the data base to use the custom Queries over the database. 
	 * @return Connection from the Data Source
	 */
	public Connection getConnection () {
		try {
			return _dataSource.getConnection();
		}
		catch (SQLException e) {
			error(e.getMessage());
		}
		return null;
	}
	
	@Override
	public String getName() {
		return "DBUtils";
	}
}